package com.cll.pmis.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.cll.pmis.common.Result;
import com.cll.pmis.common.annotation.HasPerms;
import com.cll.pmis.common.security.SecurityContext;
import com.cll.pmis.common.utils.CommonUtil;
import com.cll.pmis.common.validator.ValidatorUtils;
import com.cll.pmis.common.validator.group.Insert;
import com.cll.pmis.entity.Dossier;
import com.cll.pmis.entity.Orders;
import com.cll.pmis.service.IDossierService;
import com.cll.pmis.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 病例
 * </p>
 *
 * @author chenliangliang
 * @since 2018-06-18
 */
@RestController
@RequestMapping("/dossier")
@Slf4j
public class DossierController {

    private IDossierService dossierService;
    private IOrderService orderService;

    protected DossierController(IDossierService dossierService, IOrderService orderService) {
        this.dossierService = dossierService;
        this.orderService = orderService;
    }


    @HasPerms("dossier:insert")
    @PostMapping(value = "/add", produces = "application/json")
    public Result add(@RequestBody Dossier dossier) {
        ValidatorUtils.validateEntity(dossier, Insert.class);

        if (CommonUtil.isNumber(dossier.getUsername())) {
            return Result.paramError("用户名不能全是数字");
        }
        if (!CommonUtil.isPhone(dossier.getPhone())) {
            return Result.paramError("手机号码格式错误");
        }
        dossier.setId(null);
        dossier.setCreateTime(new Date());
        dossier.setUpdateTime(new Date());
        dossier.setDoctor(SecurityContext.getUsername());

        if (dossierService.insert(dossier)) {
            return Result.ok(dossier);
        }
        return Result.insertError();
    }


    @GetMapping("/query")
    public Result query(@RequestParam(value = "username", required = false) String username,
                        @RequestParam(value = "did", required = false) Integer did) {

        if (StringUtils.isEmpty(username) && did == null) {
            return Result.paramError();
        }
        try {
            List<Dossier> dossierList = dossierService.queryInfo(username, did);
            return Result.ok(dossierList);
        } catch (Exception e) {
            log.error("查询病例异常", e);
            return Result.selectError();
        }

    }


    @GetMapping("/list")
    public Result list(@RequestParam(value = "pageIndex", required = false) Integer pageIndex,
                       @RequestParam(value = "pageSize", required = false) Integer pageSize,
                       @RequestParam(value = "query", required = false) String query,
                       @RequestParam(value = "id", required = false) Integer id) {
        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = 4;
        }
        String username = null;
        String phone = null;
        if (StringUtils.isNotEmpty(query)) {
            if (CommonUtil.isNumber(query)) {
                phone = query;
            } else {
                username = query;
            }
        }
        EntityWrapper<Dossier> wrapper = new EntityWrapper<>();
        wrapper.eq("is_delete", 0)
                .like(id != null, "id", String.valueOf(id))
                .like(username != null, "username", username)
                .like(phone != null, "phone", phone);

        Page<Dossier> dossierPage = dossierService.selectPage(new Page<>(pageIndex, pageSize), wrapper);
        return Result.ok(dossierPage);
    }


    @HasPerms("dossier:delete")
    @PostMapping("/delete")
    public Result delete(@RequestParam(value = "dossierId", required = false) Integer dossierId) {
        if (dossierId == null) {
            return Result.paramError();
        }
        Dossier dossier = new Dossier();
        dossier.setId(dossierId);
        dossier.setIsDelete(1);
        dossier.setUpdateTime(new Date());
        if (dossierService.updateById(dossier)) {
            return Result.ok("");
        }


        return Result.fail("该病例不存在，或删除失败");
    }


    @HasPerms("dossier:update")
    @PostMapping("/update")
    public Result update(@RequestBody Dossier dossier) {
        if (dossier == null || dossier.getId() == null) {
            return Result.fail("参数异常：病例号不能为空");
        }
        if (StringUtils.isNotEmpty(dossier.getUsername()) && CommonUtil.isNumber(dossier.getUsername())) {
            return Result.paramError("用户名不能全是数字");
        }
        dossier.setUpdateTime(new Date());
        return dossierService.updateById(dossier) ? Result.ok("") : Result.updateError();
    }

    @GetMapping("/select")
    public Result select(@RequestParam("id") Integer id) {
        if (id == null) {
            return Result.paramError();
        }
        Dossier dossier = dossierService.selectById(id);
        return Result.ok(dossier);
    }


    @GetMapping("/prescribe")
    public Result prescribeInfo(@RequestParam(value = "dossierId", required = false) Integer dossierId) {
        if (dossierId == null) {
            return Result.paramError();
        }
        Dossier dossier = dossierService.selectOne(new EntityWrapper<Dossier>()
                .eq("id", dossierId)
                .eq("is_delete", 0));
        if (dossier == null) {
            return Result.fail("该病例不存在");
        }


        Orders order = orderService.selectOne(new EntityWrapper<Orders>().eq("dossier_id", dossier.getId()));
        if (order == null) {
            return Result.fail("订单不存在");
        }

        dossier.setOrderStatus(order.getStatus());
        dossier.setOrderId(order.getOrderId());
        List<Map<String, Object>> list = dossierService.getMapper().queryPrescibeInfo(order.getId());

        dossier.setList(list);

        return Result.ok(dossier);
    }

}

